import { _decorator, CCInteger, Component, Prefab, Node, instantiate, director } from "cc"
import NetworkManager from "../Global/NetworkManager"
import { ApiMsgEnum, IApiPlayerListRes, IApiRoomListRes, IMsgGameStart, IMsgRoom } from "../Common"
import { PlayerManager } from "../UI/PlayerManager"
import DataManager from "../Global/DataManager"
import { SceneEnum } from "../Enum"
import { deepClone } from "../Utils"
const { ccclass, property } = _decorator

@ccclass("RoomManager")
export class RoomManager extends Component {
    @property(Node)
    playerContainer: Node

    @property(Prefab)
    playerPrefab: Prefab

    onLoad() {
        NetworkManager.Instance.listenMsg(ApiMsgEnum.MsgRoom, this.renderPlayer, this)
        NetworkManager.Instance.listenMsg(ApiMsgEnum.MsgGameStart, this.handleGameStart, this)
    }

    start() {
        // this.playerContainer.destroyAllChildren() // 由于destory操作会延迟到当前帧渲染前执行，可能会render之后再销毁，所以这里就不destory了，在cocos里先删除所有子节点
        // 首次渲染玩家列表数据来自数据中心
        this.renderPlayer({
            room: DataManager.Instance.roomInfo
        })
    }

    onDestroy() {
        NetworkManager.Instance.unlistenMsg(ApiMsgEnum.MsgRoom, this.renderPlayer, this)
        NetworkManager.Instance.unlistenMsg(ApiMsgEnum.MsgGameStart, this.handleGameStart, this)
    }

    renderPlayer({ room: { players: list } }: IMsgRoom) {
        for (const e of this.playerContainer.children) {
            e.active = false
        }

        while (this.playerContainer.children.length < list.length) {
            const node = instantiate(this.playerPrefab)
            node.active = false
            node.setParent(this.playerContainer)
        }

        for (let i = 0; i < list.length; i++) {
            const data = list[i]
            const node = this.playerContainer.children[i]
            node.getComponent(PlayerManager).init(data)
        }
    }

    async handleLeaveRoom() {
        const { success, error, res } = await NetworkManager.Instance.callApi(
            ApiMsgEnum.ApiRoomLeave,
            {}
        )
        if (!success) {
            console.error("离开房间失败: ", error)
            return
        }

        console.log("离开房间成功")
        DataManager.Instance.roomInfo = null
        director.loadScene(SceneEnum.Hall)
    }

    async handleButtonStart() {
        const { success, error, res } = await NetworkManager.Instance.callApi(
            ApiMsgEnum.ApiGameStart,
            {}
        )
        if (!success) {
            console.error("开始游戏失败: ", error)
            return
        }
    }

    handleGameStart({ state }: IMsgGameStart) {
        DataManager.Instance.state = state
        DataManager.Instance.lastState = deepClone(state) // 游戏开始时初始化上一次服务器状态
        director.loadScene(SceneEnum.Battle)
    }
}
